package normal

import (
	"GraduationProject/public/models"
	"GraduationProject/worker/worker_tools"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"
)

var (
	client        *http.Client
	netEasyCookie = http.Cookie{
		Name:   "_ntes_nuid",
		Value:  "ff57c2c2391a39e121fc6db90f707bd7",
		Path:   "/",
		Domain: ".163.com",
		// 2039年10月3日星期一 下午8:49:12
		Expires: time.Date(2039, 10, 3, 8, 49, 12, 0, time.Local),
	}
	tick = time.Tick(time.Second * 3)
)

func init() {
	client = &http.Client{
		Timeout: time.Second * 3,
	}
}

func Get(url string) (content []byte, err error) {
	<-tick
	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}

	request.AddCookie(&netEasyCookie)
	request.Header.Add("Host", "music.163.com")
	request.Header.Add("User-Agent", worker_tools.GetUserAgent())
	request.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	response, err := client.Do(request)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	bytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}
	return bytes, err
}

func Post(_url, params string) (content []byte, err error) {
	<-tick
	body := url.Values{}
	var param []models.Param
	if err := json.Unmarshal([]byte(params), &param); err != nil {
		return nil, err
	}

	for _, v := range param {
		body[v.Key] = []string{v.Value}
	}

	request, err := http.NewRequest("POST", _url, strings.NewReader(body.Encode()))
	if err != nil {
		return nil, err
	}

	request.AddCookie(&netEasyCookie)
	request.Header.Add("Host", "music.163.com")
	request.Header.Add("User-Agent", worker_tools.GetUserAgent())
	request.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	response, err := client.Do(request)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	content, err = ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}
	return content, err
}
